<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\BlackCard\Controllers;

use App\Admin\Extensions\Tools\UploadButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\GoodsBasicInfo;
use Doraemon\service\BlackCard\GoodsToWiki;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Biz\model\wiki\Wiki as mWiki;
use Doraemon\service\BlackCard\AdminWiki as sAdminWiki;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Biz\model\GoodsExtendInfo as mGoodsExtendInfo;


class GoodsController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $tab = new Tab();
        $tab->addLink('节选商品', '/admin/blackCard', false);
        $tab->addLink('好好住商品', '/admin/blackCard/goods/index', true);

        $where = $this->buildWhere($request->all());
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);

        $limit = [
            ($page - 1) * $perPage, $perPage
        ];

        $result = sAdminWiki::getList($where, $limit);
        $grid = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $perPage
        ]);

        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->filter(function($filter){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 添加字段过滤器
                    $filter->like('channel_spu_id', '好好住商品id');
                    $filter->like('title', 'wiki名称');
                });

                $grid->disableExport();
                $grid->expandFilter();
                $grid->disableRowSelector();
                $grid->column("id", 'wiki_id');
                $grid->column("channel_spu_id", '好好住商品id');
                $grid->column("title", '标题')->width(300);
                $grid->column("cover_img", '商品头图')->image($this->cover_img, 100, 100);
                $grid->column("min_price", '最低价');
                $grid->column("max_price", '最高价');
                $grid->column("status", '状态')->display(function () {
                    return mWiki::ADM_STATUS_MAP[$this->status];
                });
                $grid->column("is_black", "是否为黑卡商品")->switchToggle();
                $grid->column('aaa', '返佣比例')->display(function () {
                    $info = mGoodsExtendInfo::get([
                        'shop_id',
                        'ratio',
                        'ratio_ext'
                    ], ['goods_id' => $this->channel_spu_id]);
                    $ratioExt = $info ? json_decode($info['ratio_ext'], true) : [];
                    $appRate = ($ratioExt && isset($ratioExt['app_sale'])) ? $ratioExt['app_sale']['ratio'] : 0;
                    return "<a href=\"https://shop-admin.haohaozhu.me/admin/goods/info/list?category_id=&field1=uid&keyword1=&field2=goods_id&keyword2={$this->channel_spu_id}&price_range%5B%5D=&price_range%5B%5D=&sell_total%5B%5D=&sell_total%5B%5D=&add_cart_num%5B%5D=&add_cart_num%5B%5D=&start_date=&stop_date=&tags_input=&status=online&only_alarm=&brand_id=-1\" target='_blank' >{$appRate}%</a>";
                });
                $grid->disableActions();
            });

        return $content
            ->header('黑卡小程序goods')
            ->body($tab)
            ->row($gridList)
            ->description(' ')
            ->breadcrumb(['text' => 'wiki']);
    }

    public function setBlack($wikiId, Request $request)
    {
        $message = '修改成功';
        try {
            $isBlack = $request->input('is_black', null);
            $name    = $request->input('name', null);
            $value   = $request->input('value', null);

            if(!is_null($isBlack)) {
                $isBlack = $isBlack == 'on' ? 1 : 0;
                $result = mWiki::updateData(['is_black' => $isBlack], ['id' => $wikiId]);
            }

            if(!$result) {
                throw new \Exception('修改失败');
            }
            $status = true;
        } catch (\Exception $e) {
            $message = $e->getMessage();
            $status = false;
        }

        $response = compact('status', 'message');
        return response()->json($response);
    }

    public function create(Request $request,Content $content)
    {
        $request = $request->all();

        $data = [];
        $form = new Form($data);
        $form->text('goods_id', '好好住商品id')->setWidth(4, 2)->required('不能为空')->help("多个商品id可用,分割。");
        $form->action('/admin/blackCard/goods/index/submit');
        $form_body = $form->render();

        return $content
            ->header('黑卡好好住商品 - 添加')
            ->body($form_body);
    }

    public function submit(Request $request)
    {
        $request = $request->all();
        $goods_ids_str = $request['goods_id'];
        $goods_ids = explode(",", $goods_ids_str);
        foreach ($goods_ids as $goods_id){
            if (!is_numeric($goods_id)){
                $error = new MessageBag([
                    'title' => "goods_id格式错误"
                ]);
                return back()->with(compact('error'));
            }

            $goods_basic_info = GoodsBasicInfo::getGoodsInfoByGoodsId("*", $goods_id);
            if (empty($goods_basic_info)){
                $error = new MessageBag([
                    'title' => "goods_id:{$goods_id}不存在"
                ]);
                return back()->with(compact('error'));
            }
        }

        foreach ($goods_ids as $goods_id){
            (new GoodsToWiki($goods_id))->getItemDetail()->itemToWiki();
        }

        $success = new MessageBag([
            'title' => '添加成功'
        ]);
        return redirect('/admin/blackCard/goods/index')->with(compact('success'));
    }

    private function buildWhere($params)
    {
        $where = [];
        if(isset($params['channel_spu_id']) && $params['channel_spu_id']) {
            $where['channel_spu_id'] = $params['channel_spu_id'];
        }

        if(isset($params['title']) && $params['title']) {
            $where['title[~]'] = $params['title'];
        }

        $where['channel'] = mWiki::CHANNEL_HAOHAOZHU;

        return $where;
    }
}